package br.com.inner.dao;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.inner.custom.CustomException;
import br.com.inner.custom.JPAManager;
import br.com.inner.modelo.UF;

public class UFDBDao implements UFDao{

	private static UF ufs;
	/*static{
		JPAManager.createEntityManagerFactory("inner");
	}*/
        
	public UF getUF(BigDecimal cdUf) throws CustomException{
		EntityManager em = JPAManager.getEntityManager();
		Query q = em.createNamedQuery("UF");
		q.setParameter("cdUf", cdUf);
		ufs = (UF)q.getSingleResult();
		//JPAManager.commitTransaction();
		return ufs;
	}
	
	public UF getAll() throws CustomException{
		String sql = "Select t from UF";
		sql += " t ";
		EntityManager em = JPAManager.getEntityManager();
		Query q = em.createQuery(sql);
		//JPAManager.commitTransaction();
		return (UF)q.getResultList();
	}
    
	@SuppressWarnings("unchecked")
    public List<UF> getAllUFs() throws CustomException{
    	
    	EntityManager em = JPAManager.getEntityManager();
    	//em.clear();
    	//JPAManager.beginTransaction();
    	String sql = "Select t from UF t";
    	Query q = em.createQuery(sql);
		//JPAManager.commitTransaction();
		return q.getResultList();
    }
    
	public void insert(UF uf){
		
		try {
			uf.generatePK();
			EntityManager em = JPAManager.getEntityManager();
			JPAManager.beginTransaction();
			em.persist(uf);
			JPAManager.commitTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			JPAManager.rollbackTransaction();
			e.printStackTrace();
		}
	}
	
	public void update(UF uf){
		try{
			EntityManager em = JPAManager.getEntityManager();
			JPAManager.beginTransaction();
			UF uf1 = new UF();
			uf1 = em.find(UF.class, uf.getCdUf());
			uf1.setDsUf(uf.getDsUf());
			em.merge(uf1);
			JPAManager.commitTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			JPAManager.rollbackTransaction();
			e.printStackTrace();
		}
	}
	
	public void delete(BigDecimal cdUf) throws CustomException{
		try {
			UF uf1 = null;
			EntityManager em = JPAManager.getEntityManager();
			JPAManager.beginTransaction();
			Query q = em.createNamedQuery("UF");
			q.setParameter("cdUf", cdUf);
			uf1 = (UF)q.getSingleResult();
			em.remove(uf1);
			//em.flush();
			JPAManager.commitTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			JPAManager.rollbackTransaction();
			System.out.println("Erro no CategoriaDBDao");
			throw new CustomException("Erro no CategoriaDBDao");
		}
	}
}